/*
* @file_name: thread_pool.h
* @date: 2021/08/30
* @author: oaho
* Copyright @ hz oaho, All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef OAHO_TASK_EXECUTOR_POOL_H
#define OAHO_TASK_EXECUTOR_POOL_H
#include <map>
#include <future>
#include <algorithm>
#include <type_traits>
#include "nocopyable.hpp"
#include "singleton.hpp"
#include <atomic>
#include <thread>
class round_robin {
public:
	using value_type =  std::thread::id;
public:
	template<typename Container> round_robin(Container&);
	template<typename Container> inline typename Container::value_type::second_type get(Container&);
	template<typename Container, typename F> inline void put(Container&, F&&);
private:
	value_type _current_;
};


template<typename TaskExecutor>
class thread_pool : public noncopyable {
	friend class singleton<thread_pool<TaskExecutor>>;
public:
	using container = std::map<std::thread::id, std::shared_ptr<TaskExecutor>>;
public:
	inline void stop();
	inline const std::thread::id get_current_thread_id();
	/* @fetch_current_thread: get current thread */
	template<typename policy>
	inline TaskExecutor& get_poller(bool fetch_current_thread = true);
	~thread_pool();
private:
	thread_pool(size_t thread_num = std::thread::hardware_concurrency());
	inline void start();
	template<typename F, typename...Args> inline void async(F&&, Args&&...);
private:
	void init();
private:
	size_t thread_num;
	container _pool_;
	std::atomic<bool> running;
};




#endif